package com.net.oil.http.custom;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.net.oil.bean.BaseBean;
import com.net.oil.http.AppHttpCode;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * 作者：lch
 * 时间：2017/12/14:10:11
 * 邮箱：245850413@qq.com
 * 说明：
 */

public class CustomGsonResponseBodyConverter <T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    CustomGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        String response = value.string();
        BaseBean resultBean = gson.fromJson(response, BaseBean.class);
        if (resultBean != null && !resultBean.isCodeSuccess()) {
            value.close();
            throw new ApiException(resultBean.getCode(), resultBean.getMsg());
        } else if (resultBean == null) {
            value.close();
            throw new ApiException(AppHttpCode.ERROR, "请求错误");
        }

        MediaType contentType = value.contentType();
        Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8;
        InputStream inputStream = new ByteArrayInputStream(response.getBytes());
        Reader reader = new InputStreamReader(inputStream, charset);

        JsonReader jsonReader = gson.newJsonReader(reader);
        try {
            return adapter.read(jsonReader);
        } finally {
            value.close();
        }
    }
}
